<?php

namespace App\Http\Controllers\Admin;

use App\Http\Model\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Captcha;
use Illuminate\Support\Facades\Input;

class RegLoginController extends Controller
{
    /**
     * 用户登录
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     */
    public function login()
    {
        if($input = Input::all())
        {
            if(strtolower($input['yzm'])!==strtolower(session('yzm')))
            {
                return back()->with('login_msg','验证码错误');
            }
            $ret=User::where('user_email',$input['email'])->first();
            if($ret&&md5($input['password'])===$ret->user_password)
            {
                session(['user_id'=>$ret->user_id]);
                return redirect('charge/index.html');
            }else{
                return back()->with('login_msg','密码或账号错误');
            }

        }else{
            return view('admin/login');
        }

    }

    /**
     * 用户注册表单
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function reg()
    {
        return view('admin/reg');
    }

    /**
     * 注册表单提交
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function reg_post(Request $request)
    {
       if(strtolower($request->all()['yzm'])!=strtolower(session('yzm')))
       {
           return back()->with('yzm_error','验证码错误');
       }
        $message=[
            'email.required'=>'邮箱不能为空',
            'email'=>'邮箱格式不正确',
            'unique'=>'邮箱已经被注册',
            'password.required'=>'密码不能为空',
            'name.required'=>'昵称不能为空',
        ];

        $this->validate($request,[
            'yzm'=>'required',
            'email'=>'bail|required|email|unique:user,user_email',
            'name'=>'required',
            'password'=>'required',
        ],$message);
        $User = new User;
        $User->user_name=$request->name;
        $User->user_email=$request->email;
        $User->user_password=md5($request->password);
        $User->user_key=md5(time());
        $User->save();
        return redirect('charge/login.html');

    }

    /**
     * 验证码生成
     * @return 图片数据
     */
    public function yzm(){
        $captcha = new Captcha(80,35,4);
        session(['yzm'=>$captcha->getcode()]);
        return $captcha->outimg();
    }
}
